package com.rookie.im.learn.io.netty.protocol.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.HashSet;
import java.util.Set;

/**
 * Handles a server-side channel.
 */
public class DiscardServerHandler extends ChannelInboundHandlerAdapter { // (1)

    static Set<Channel> channelSet = new HashSet<>();
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端" + ctx.channel().remoteAddress() + "连接");
        channelSet.forEach(ch->{
            ch.writeAndFlush("[客户端]:" + ctx.channel().remoteAddress() + "连接");
        });
        channelSet.add(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端" + ctx.channel().remoteAddress() + "断开");
        channelSet.remove(ctx.channel());
        channelSet.forEach(ch->{
            ch.writeAndFlush("[客户端]:" + ctx.channel().remoteAddress() + "断开");
        });
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)
        channelSet.forEach(ch->{
            StringBuilder buf = new StringBuilder();
            if (ch == ctx.channel()) {
                buf.append("[自己]: ");
            } else {
                buf.append("[客户端]: ");
            }
            buf.append(msg);
            ch.writeAndFlush(buf.toString());
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}